/**
    ATClab - scriptable Air Traffic Control simulations.
    Copyright (C) 2010 openatclab@gmail.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**/

#include "factory.h"
#include "exception.h"
#include "performance.h"


using namespace performance;

////////////////////////////////////////////////////////////////////////////////
//
// performance::Factory
//
//------------------------------------------------------------------------------
//
//

/*!
 *
 */
Factory * Factory::_instance = 0;

/*!
 *
 */
Factory::Factory( std::auto_ptr< Data > data )
	  : _data( data )
{}
  
/*!
 *
 */
Factory::~Factory() {
	PerformanceMap::const_iterator it = _map.begin();
	for ( ; it != _map.end(); ++it ) {
		delete it->second;
	}
}
  
//------------------------------------------------------------------------------
//
//
  
/*!
 * Initialize the factory with the performance data
 *
 * The factory will take ownership of the performance data object.
 */
void Factory::initialize( std::auto_ptr< Data > data ) {
	if ( _instance )
		throw performance_data_error( "factory already initialized" );

	_instance = new Factory( data );
}

void Factory::destroy() {
	if ( _instance ) delete _instance;
	_instance = 0;
}

/*!
 *
 */
const Performance * Factory::performance( const char *id ) {
	if ( ! _instance ) 
		throw performance_data_error( "factory not initialized" );

	PerformanceMap::iterator it = _instance->_map.find( id );
	if ( _instance->_map.end() != it ) {
		return it->second;
	}
	else {
		const PDT *type = _instance->_data->lookup_type( id );
		const PDO *data = _instance->_data->lookup_data( type->classRef );
		Performance* p = new Performance( type, data );
		_instance->_map[ id ] = p;
		return p;
	}
}

////////////////////////////////////////////////////////////////////////////////
